package com.spring.demo.redis.utils;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class JedisUtil2 {
    private static JedisPool jedisPool = null;

    static {
        InputStream resourceAsStream = JedisUtil2.class.getClassLoader().getResourceAsStream("jedis.properties");
        Properties properties = new Properties();
        try {
            properties.load(resourceAsStream);
            String host = properties.getProperty("host");
            String port = properties.getProperty("port");
            String maxIdle = properties.getProperty("maxIdle");
            String maxTotal = properties.getProperty("maxTotal");

            JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
            // 最大空闲数
            jedisPoolConfig.setMaxIdle(Integer.valueOf(maxIdle));
            // 最大连接数
            jedisPoolConfig.setMaxTotal(Integer.valueOf(maxTotal));

            jedisPool = new JedisPool(jedisPoolConfig, host, Integer.valueOf(port));

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获得Jedis
     *
     * @return
     */
    public static Jedis getJedis() {
        return jedisPool.getResource();
    }

    /**
     * 释放资源
     *
     * @param jedis
     */
    public static void closeJedis(Jedis jedis) {
        jedis.close();
    }
}